// eslint-disable-next-line no-unused-vars
import VXETable, { Column } from 'vxe-table'
import ImageUpload from '../../../components/ImageUpload'
import isFunction from 'lodash/isFunction'
import createBem from '@Components/assets/js/utils/bem'
import { tableNamespace } from '../../../config'
import { ImgUrlFilter } from '@Components/assets/js/filter'
import './index.scss'

const Bem = createBem(`${tableNamespace}__upload`)

VXETable.renderer.add('Upload', {
  renderDefault(h, renderOpts, { row, column }) {
    const { $tableInstance, events = {}, options = {} } = renderOpts
    const { objectKey, limit, disabled, active = true } = options
    const { onUpload } = events
    /**
     * @type { Array<string> }
     */
    const rawImages = row[column.property] || []

    let imageList = []
    if (rawImages instanceof Array) {
      imageList = rawImages.map(i => {
        return objectKey ? i[objectKey] : i
      })
    } else {
      imageList = [rawImages]
    }

    //预览
    function handleShowViewer() {
      $tableInstance.updateViewer(imageList.map(i => ImgUrlFilter(i)))
    }

    /** @param { Array<string> } images */
    //上传成功
    function handleImageSave(images) {
      onUpload?.({ images, row, column })
    }

    let _disabled = disabled
    if (typeof disabled === 'function') {
      _disabled = disabled({ cellValue: rawImages, row, column })
    }

    return [
      <div class={Bem()}>
        <ImageUpload
          images={imageList}
          limit={limit}
          disabled={_disabled}
          active={
            isFunction(active)
              ? active({ images: rawImages, row, column })
              : active
          }
          onView={handleShowViewer}
          onSave={handleImageSave}
        />
      </div>
    ]
  }
})

/** @type { Column } */
export const options = {
  showOverflow: 'ellipsis',
  align: 'center'
}
